/**
 * TanStack Query 客户端配置
 */
import {QueryClient} from '@tanstack/react-query';

/**
 * 全局 Query Client 配置
 */
export const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            // 缓存时间：5分钟内数据视为新鲜
            staleTime: 5 * 60 * 1000,
            // 缓存保留时间：10分钟
            gcTime: 10 * 60 * 1000,
            // 窗口焦点时自动重新获取数据
            refetchOnWindowFocus: true,
            // 网络重连时自动重新获取
            refetchOnReconnect: true,
            // 失败时重试次数
            retry: 1,
            // 重试延迟（指数退避）
            retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
        },
        mutations: {
            // Mutation 失败时重试1次
            retry: 1,
        },
    },
});

/**
 * Query Keys 常量定义
 * 用于标识不同的查询缓存
 */
export const QueryKeys = {
    // Spaces 相关
    spaces: ['spaces'] as const,
    space: (id: number) => ['spaces', id] as const,

    // Collections 相关
    collections: (spaceId: number) => ['spaces', spaceId, 'collections'] as const,
    collection: (id: number) => ['collections', id] as const,

    // Tabs 相关
    tabs: (collectionId: number) => ['collections', collectionId, 'tabs'] as const,
    tabsByCollections: (spaceId: number, collectionIds: number[]) =>
        ['spaces', spaceId, 'tabs', 'batch', ...collectionIds] as const,
    tab: (id: number) => ['tabs', id] as const,
} as const;
